package com.congee02.bt.dfs.top2bottom;

import com.congee02.bt.TreeNode;

public class MaxAncestorDiff {

    public int maxAncestorDiff(TreeNode root) {
        return Math.max(
                process(root.left, root.val, root.val),
                process(root.right, root.val, root.val)
        );
    }

    private int process(TreeNode cur, int min, int max) {
        if (cur == null) {
            return -1;
        }
        int curDiff = Math.max( Math.abs(cur.val - min), Math.abs(cur.val - max) );
        if (cur.left == null && cur.right == null) {
            return curDiff;
        }

        int curMin = Math.min(min, cur.val);
        int curMax = Math.max(max, cur.val);

        return Math.max(
                curDiff,
                Math.max(
                        process(cur.left, curMin, curMax),
                        process(cur.right, curMin, curMax)
                )
        );
    }

}
